﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LabChecker.Models;

namespace LabChecker.Controllers
{ 
    [Authorize]
    public class TestCaseController : Controller
    {
        private LabCheckerContext db = new LabCheckerContext();

        public ViewResult Index(int taskId)
        {
            var task = db.Tasks.Find(taskId);

            ViewBag.Task = task;

            return View(task.TestCases.OrderBy(t => t.Index));
        }        

        public ActionResult Create()
        {
            return View();
        } 
      
        [HttpPost]
        public ActionResult Create(TestCase testcase)
        {
            if (ModelState.IsValid)
            {
                db.TestCases.Add(testcase);
                db.SaveChanges();
                return RedirectToAction("Index");  
            }

            return View(testcase);
        }        
 
        public ActionResult Edit(int id)
        {
            TestCase testcase = db.TestCases.Find(id);
            return View(testcase);
        }

        [HttpPost]
        public ActionResult Edit(int id, FormCollection formCollection)
        {
            var testCase = db.TestCases.Find(id);

            if (TryUpdateModel(testCase))
            {
                db.SaveChanges();
                return RedirectToAction("Index", new { taskId = testCase.Task.Id });
            }
            
            return View(testCase);
        }

        public ActionResult Delete(int id)
        {
            TestCase testcase = db.TestCases.Find(id);
            return View(testcase);
        }

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {            
            TestCase testcase = db.TestCases.Find(id);
            db.TestCases.Remove(testcase);
            db.SaveChanges();
            return RedirectToAction("Index", new { taskId = testcase.Task.Id });
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}